package com.itheima.service.mongo;

import com.itheima.domain.mongo.SoundTime;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@Service
public class SoundTimeServiceImpl implements SoundTimeService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void update(SoundTime soundTime) {
        Query query = new Query(
                Criteria.where("userId").is(soundTime.getUserId())
        );
        mongoTemplate.updateFirst(query,new Update().set("remainingTimes",soundTime.getRemainingTimes()),SoundTime.class);
    }

    @Override
    public void save(Long userId,Integer remainingTimes) {
        SoundTime soundTime = new SoundTime();
        if (soundTime == null) {
            soundTime = new SoundTime();
            soundTime.setCreated(System.currentTimeMillis());
            soundTime.setUserId(userId);
            soundTime.setRemainingTimes(remainingTimes);
        }
        soundTime.setCreated(System.currentTimeMillis());
        soundTime.setUserId(userId);
        soundTime.setRemainingTimes(remainingTimes);
        mongoTemplate.save(soundTime);
    }

    @Override
    public SoundTime findById(Long userId) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
        ).with(Sort.by(Sort.Order.desc("created")))
                .skip(0).limit(1);
        SoundTime soundTime = mongoTemplate.findOne(query, SoundTime.class);
        return soundTime;
    }
}
